package com.controller;


import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Random;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.po.Image;
import com.service.ImageService;


@Controller("/image")
@RequestMapping("/image")
public class ImageController {
	@Autowired
	private ImageService imageService;

	
	@RequestMapping(value = "/simpleFileupload")
	public String detail(Model model){
	
	    return  "image/simpleFileupload";
	}
	@RequestMapping(value = "/list")
	public String list(Model model){
		List <Image> paging = imageService.List();
		model.addAttribute("List", paging);
	    return  "image/list";
	}
	@RequestMapping(value = "/del")
	public String del(@RequestParam(value="id") Integer id){
		imageService.del(id);
	    return "redirect:/image/list.htm";
	}
	
	/*@RequestMapping(value = "/edit")
	protected String doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {  
		
		String path ="http://192.168.88.201:8081/";
        request.setCharacterEncoding("utf-8");  
        response.setCharacterEncoding("utf-8");  
        //1、创建一个DiskFileItemFactory工厂  
        DiskFileItemFactory factory = new DiskFileItemFactory();  
        //2、创建一个文件上传解析器  
        ServletFileUpload upload = new ServletFileUpload(factory);  
        //解决上传文件名的中文乱码  
        upload.setHeaderEncoding("UTF-8");   
        factory.setSizeThreshold(1024 * 500);//设置内存的临界值为500K  
        File linshi = new File(request.getServletContext().getRealPath("/static/echarts/upload"));//当超过500K的时候，存到一个临时文件夹中  
        factory.setRepository(linshi);  
        try {  
            // 1. 得到 FileItem 的集合 items  
            List<FileItem>  FileItem items = upload.parseRequest(request);  
            Image image = new Image();
            // 2. 遍历 items:  
            for (FileItem item : items) {  
                // 若是一个一般的表单域, 打印信息  
                if (item.isFormField()) {  
                    String name = item.getFieldName();  
                    String value = item.getString("utf-8");  
                    if(item.getFieldName().equals("number"))
                    {
                    	image.setNumber(Integer.parseInt(value));  
                    }  
                }  
                else {  
                    String fileName = new String(item.getName().getBytes("ISO8859_1"),"UTF-8"); 
                    long sizeInBytes = item.getSize();  
                    System.out.println(fileName);  
                    System.out.println(sizeInBytes);  
                    InputStream in = item.getInputStream();  
                    byte[] buffer = new byte[1024];  
                    int len = 0;  
                    String str= "http://192.168.88.201:8081/ROOT"+"/static/echarts/upload"+ "/"+fileName;
                    image.setImgurl(str);
                    fileName = request.getServletContext().getRealPath("/static/echarts/upload")+ "/"+fileName;//文件最终上传的位置  
                    OutputStream out = new FileOutputStream(fileName); 
                 
                    while ((len = in.read(buffer)) != -1) {  
                        out.write(buffer, 0, len);  
                    }  
                    out.close();  
                    in.close();                		 
                }  
            } 
            System.out.println("ImageURl"+image.getImgurl());
            System.out.println("Number"+image.getNumber());
            
            imageService.add(image);
          
            
        } catch (FileUploadException e) {  
            e.printStackTrace();  
        }  
        return "redirect:/image/list.htm";
    } */
	

		 
	
	 
	    @RequestMapping(value = "/upload", method = RequestMethod.POST)
	    public String upload(@RequestParam("file") MultipartFile tmpFile, HttpServletRequest request) {
	        ModelAndView modelAndView = new ModelAndView("fileupload");
	 
	        if (tmpFile != null) {
	            // 获取物理路径
	            String targetDirectory = request.getSession().getServletContext().getRealPath("/static/echarts/uploads");
	            String tmpFileName = tmpFile.getOriginalFilename(); // 上传的文件名
	            int dot = tmpFileName.lastIndexOf('.');
	            String ext = "";  //文件后缀名
	            if ((dot > -1) && (dot < (tmpFileName.length() - 1))) {
	                ext = tmpFileName.substring(dot + 1);
	            }
	            // 其他文件格式不处理
	            if ("png".equalsIgnoreCase(ext) || "jpg".equalsIgnoreCase(ext) || "gif".equalsIgnoreCase(ext)) {
	                // 重命名上传的文件名
	              //  String targetFileName = this.renameFileName(tmpFileName);
	                // 保存的新文件
	                File target = new File(targetDirectory, tmpFileName);
	 
	                try {
	                    // 保存文件
	                    FileUtils.copyInputStreamToFile(tmpFile.getInputStream(), target);
	                } catch (IOException e) {
	                    e.printStackTrace();
	                }
	 
	                Image u = new Image();
	                u.setImgurl(request.getContextPath() + "/static/echarts/uploads/" + tmpFileName);
	              
	                modelAndView.addObject("u", u);
	                imageService.add(u);
	            }
 
	        }
	        return "redirect:/image/list.htm";
	        

	 
	}
}
